﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PMS.SANY.Entity;
using PMS.SANY.IBusiness;
using System;
using System.Threading.Tasks;

namespace PMS.SANY.OpenApi.Controllers
{
    [ApiController]
    public class SANYController : ControllerBase
    {
        public IPlanBusiness Bus { get; set; }
        public IOprSequenceBusiness OprBus { get; set; }
        public IComponentBusiness ComBus { set; get; }
        private readonly ILogger<SANYController> _logger;

        public SANYController(IPlanBusiness bus, IOprSequenceBusiness oprBus, IComponentBusiness comBus, ILogger<SANYController> logger)
        {
            this.Bus = bus;
            this.OprBus = oprBus;
            this.ComBus = comBus;

            this._logger = logger;
        }

        /// <summary>
        /// 下发
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[controller]/gateway/pdev/sany/slaveId/task/post")]
        public async Task<ReturnData> Post([FromBody] RequestMsgHeader requestMsg)
        {
            _logger.LogInformation(string.Format("开始接收请求参数 taskId:{0},taskType:{1},task:{2}", requestMsg.taskId, requestMsg.taskType, requestMsg.task));
            var rust = new ReturnData();
            try
            {
                //ReceivedDataController receivedData = new ReceivedDataController(_context, _ReceivedDatalogger);
                switch (requestMsg.taskType)
                {
                    //生产订单下发
                    case "51":
                        var task = JsonConvert.DeserializeObject<WipOrderModel>(requestMsg.task.ToString());
                        rust = await SaveWipOrderAsync(requestMsg.taskId, task);
                        //rust = await receivedData.AddPBOrderAsync(task);
                        break;
                    //AGV搬运反馈信息确认到中控接口
                    case "10":
                        var session = JsonConvert.DeserializeObject<AGVSession>(requestMsg.task.ToString());
                        //rust = receivedData.SelectAGVSession(session);
                        break;

                    default:
                        break;
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex.Message);
            }
            return rust;
        }

        private async Task<ReturnData> SaveWipOrderAsync(string taskId, WipOrderModel model)
        {
            ReturnData result = new ReturnData();
            result.version = "1.0.0";
            result.returnData = "[]";

            try
            {
                var sucessed= await SavePlanAsync(taskId, model);

                if(sucessed)
                {
                    var idx = 1;
                    foreach (var item in model.OprSequenceList)
                    {
                        var OprId = string.Format("{0}_{1}", model.WipOrderNo, idx.ToString().PadLeft(3, '0'));
                        await SaveOprSequenceAsync(model, item, OprId);

                        if (item.ComponentList != null && item.ComponentList.Count > 0)
                        {
                            var idy = 1;
                            foreach (var comp in item.ComponentList)
                            {
                                var componentId = string.Format("{0}_{1}", OprId, idy.ToString().PadLeft(3, '0'));
                                if (!string.IsNullOrWhiteSpace(comp.MaterialNo))
                                {
                                    await SaveCompontAsync(OprId, comp, componentId);
                                }
                                idy += 1;
                            }
                        }

                        idx += 1;
                    }

                    result.code = "0";
                    result.taskId = model.WipOrderNo;
                    result.msg = "生产订单接收成功!";
                }
                else
                {
                    result.code = "501";
                    result.taskId = model.WipOrderNo;
                    result.msg = "生产订单接收失败,当前订单已下发至生产线!";
                    _logger.LogError($"生产订单接收异常,原因：当前订单已下发至生产线");
                }
            }
            catch (Exception ex)
            {
                result.code = "501";
                result.taskId = model.WipOrderNo;
                result.msg = "生产订单接收失败!";
                _logger.LogError($"生产订单接收异常,原因：{ex.Message}");
            }

            return result;
        }

        private async Task SaveCompontAsync(string OprId, ComponentList comp, string componentId)
        {
            await this.ComBus.AddOrUpdateAsync(new Component()
            {
                Id = componentId,
                MaterialAlias = comp.MaterialAlias,
                MaterialName = comp.MaterialName,
                MaterialNo = comp.MaterialNo,
                OprSequenceId = OprId,
                Quantity = comp.Quantity,
                ReserveLineNo = comp.ReserveLineNo,
                ReserveNo = comp.ReserveNo,
                Unit = comp.Unit,
                paramRsrv1 = comp.paramRsrv1,
                paramRsrv2 = comp.paramRsrv2,
                paramRsrv3 = comp.paramRsrv3,
                paramRsrv4 = comp.paramRsrv4,
                paramRsrv5 = comp.paramRsrv5,
                CreateTime = DateTime.Now,
                CreateUserId = "1",
                ModifyTime = DateTime.Now,
                ModifyUserId = "1",
                Deleted = false,
            });
        }

        private async Task SaveOprSequenceAsync(WipOrderModel model, OprSequenceModel item, string OprId)
        {
            await this.OprBus.AddOrUpdateAsync(new OprSequence()
            {
                Id = OprId,
                OprSequenceName = item.OprSequenceName,
                OprSequenceNo = item.OprSequenceNo,
                OprSequenceType = item.OprSequenceType,
                PlanId = model.WipOrderNo,
                ProgressStatus = item.ProgressStatus,
                Quantity = item.Quantity,
                ScheduledCompleteDate = item.ScheduledCompleteDate,
                ScheduledStartDate = item.ScheduledStartDate,
                SequenceNo = item.SequenceNo,
                WorkCenter = item.WorkCenter,
                WorkCenterName = item.WorkCenterName,
                WorkStation = item.WorkStation,
                WorkStationName = item.WorkStationName,
                paramRsrv1 = item.paramRsrv1,
                paramRsrv2 = item.paramRsrv2,
                paramRsrv3 = item.paramRsrv3,
                paramRsrv4 = item.paramRsrv4,
                paramRsrv5 = item.paramRsrv5,
                CreateTime = DateTime.Now,
                CreateUserId = "1",
                ModifyTime = DateTime.Now,
                ModifyUserId = "1",
                Deleted = false,
            });
        }

        private async Task<bool> SavePlanAsync(string taskId, WipOrderModel model)
        {
            Plan entity = new Plan()
            {
                Id = model.WipOrderNo,
                Facility = model.Facility,
                GroupCount = model.GroupCount,
                MonTaskId = taskId,
                paramRsrv1 = model.paramRsrv1,
                paramRsrv2 = model.paramRsrv2,
                paramRsrv3 = model.paramRsrv3,
                paramRsrv4 = model.paramRsrv4,
                paramRsrv5 = model.paramRsrv5,
                ProductAlias = model.ProductAlias,
                ProductionLine = model.ProductionLine,
                ProductName = model.ProductName,
                ProductNo = model.ProductNo,
                ProgressStatus = model.ProgressStatus,
                Quantity = model.Quantity,
                ActQuantity = 0,
                ScheduledCompleteDate = model.ScheduledCompleteDate,
                ScheduledStartDate = model.ScheduledStartDate,
                WipOrderGroup = model.WipOrderGroup,
                WipOrderNo = model.WipOrderNo,
                WipOrderType = model.WipOrderType,
                WorkCenter = model.WorkCenter,
                SerialNo = JsonConvert.SerializeObject(model.SerialNo),
                CreateTime = DateTime.Now,
                CreateUserId = "1",
                Deleted = false,
                Status = PlanStatus.Accept,
                ModifyTime = DateTime.Now,
                ModifyUserId = "1",
            };

            var dbEntity = await Bus.GetAsync(entity.Id);
            if (dbEntity != null)
            {
                if(entity.Status== PlanStatus.Accept)
                {
                    entity.CreateTime = dbEntity.CreateTime;
                    entity.Status = dbEntity.Status;
                    entity.ActQuantity = dbEntity.ActQuantity;

                    await Bus.UpdateAsync(entity);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                await Bus.AddAsync(entity);
                return true;
            }
        }
    }
}
